import 'package:get/get.dart';
import 'package:inmotion_pro/config/const.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_vehicle.dart';
import 'package:inmotion_pro/pages/mixin/cache_mixin.dart';
import 'package:inmotion_pro/pages/mixin/http_request_mixin.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:inmotion_pro/utils/string_util.dart';
import 'package:lx_widgets_library/alert/loading.dart';

class LaunchService extends GetxService with CacheMixin, HttpRequestMixin {
  // 启动服务
  static LaunchService get to => Get.find();

  @override
  void onInit() {
    super.onInit();
    _getIpGeo();
  }

  // 是否已经检查过车辆缓存
  bool _hasCheckedVehicleCache = false;

  // 获取IP地理位置
  Future<void> _getIpGeo() {
    return ApiHelper().getIpGeo().then((phoneCode) {
      GlobalService.to.phoneCode.value =
          LxStringUtil.reverseAreaCode(phoneCode);
      GlobalService.to.isChinaRegion.value = phoneCode == chinesePhoneCode;
      return Future.value();
    });
  }

  // 检查授权车辆
  Future<bool> checkAuthorizedVehicle() async {
    if (_hasCheckedVehicleCache) {
      return Future.value(false);
    }
    if (GlobalService.to.isLoggedIn) {
      if (GlobalService.to.cacheVehicleList.isNotEmpty) {
        // 本地已有缓存车辆，不再检查
        _hasCheckedVehicleCache = true;
        // 再次请求授权车辆列表，确保数据最新
        httpRequestMixinOnlyRequestAuthorizedVehicleList().then((vehicleList) =>
            cacheMixinAuthorizedVehicleWriteToCache(vehicleList));
        return Future.value(false);
      } else {
        if (!GlobalService.to.isLoggedIn) {
          // 未登录状态不检查车辆缓存
          return Future.value(false);
        }
        // 获取最近一次授权车辆列表并缓存
        Loading.showLoading(null);
        return ApiHelper()
            .getAuthorizedVehicleList(recently: true)
            .then((vehicleList) async {
          // 将车辆列表缓存到本地，并刷新全局缓存的车辆列表
          await cacheMixinAuthorizedVehicleWriteToCache(vehicleList,
              isSelected: true);
          _hasCheckedVehicleCache = true;
          // 再次请求授权车辆列表，确保数据最新
          httpRequestMixinOnlyRequestAuthorizedVehicleList().then(
              (vehicleList) =>
                  cacheMixinAuthorizedVehicleWriteToCache(vehicleList));
          return Future.value(true);
        }).whenComplete(() => Loading.dismiss());
      }
    } else {
      return Future.value(false);
    }
  }
}
